﻿package com.SoftwareManage.controller;

import com.SoftwareManage.entity.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    private final static Logger logger = LoggerFactory.getLogger(CaeController.class);


    //跳转到login登录页面
    @RequestMapping("/login")
    public String toLogin(){
        logger.info("------跳转到登录页面------");
        return "login";
    }

    //注销
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String loginout() {
        Subject subject= SecurityUtils.getSubject();
        subject.logout();
        logger.info("------用户已注销------");
        return "login";
    }

    //登录验证
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result loginPost(String username, String password, String txtCode, HttpSession session) {
        Result result = new Result();
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            user.login(token);
        } catch (UnknownAccountException e) {
            result.setMsg("账号不存在");
            return result;
        } catch (DisabledAccountException e) {
            result.setMsg("账号未启用");
            return result;
        } catch (IncorrectCredentialsException e) {
            result.setMsg("密码错误");
            return result;
        } catch (RuntimeException e) {
            result.setMsg("未知错误,请刷新界面重新登录！重复登录没用请加群联系作者带上报错截图"+e.getMessage());
            return result;
        }
        // 比对验证码是否正确
        if ( !(txtCode.equals(session.getAttribute("code") ) ) ) {
            result.setMsg("验证码错误");
            return result;
        }
        result.setSuccess(true);
        return result;
    }


    //跳转到index页面
    @RequestMapping("/index")
    public String toIndex(HttpSession session,Model model){
        logger.info("------跳转到index页面------");
        model.addAttribute("username",session.getAttribute("username"));
        return "index";
    }

}
